import { useRef, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import useSWR from "swr";

function StudentInfo(props) {
    const formRef = useRef(null);
    let navigate = useNavigate();
    const { stuSn } = useParams();

    console.log(`stuSn: ${stuSn}`);

    // 如果stuSn的值为"new"表示空表单，给useSWR一个null无需下载数据
    // 否则以stuSn的值作为学生序号，获取其学生信息至stuinfo变量
    const { data: stuinfo, error } = useSWR(
        stuSn !== "new" ? `/api/student/${stuSn}` : null
    );

    //　空表单或获取学生信息后，给表单设置初始值
    useEffect(() => {
        if (!formRef.current) return;

        const elements = formRef.current.elements;

        if (stuSn === "new") {
            // 空表单
            elements.stu_no.value = "";
            elements.stu_name.value = "";
            elements.gender.value = "";
            elements.enrolled.value = "";
            return;
        }

        if (!stuinfo) return;

        elements.stu_no.value = stuinfo.stu_no ?? "";
        elements.stu_name.value = stuinfo.stu_name ?? "";
        elements.gender.value = stuinfo.gender ?? "";
        elements.enrolled.value = stuinfo.enrolled ?? "";
    }, [stuSn, stuinfo]);

    const saveAction = async () => {
        if (!formRef.current) return;

        const elements = formRef.current.elements;
        let data = {
            stu_sn: stuSn === "new" ? null : stuSn,
            stu_no: elements.stu_no.value,
            stu_name: elements.stu_name.value,
            gender: elements.gender.value,
            enrolled: elements.enrolled.value,
        };

        let url = "/api/student";
        if (stuSn !== "new") {
            url += `/${stuSn}`;
        }

        let response = await fetch(url, {
            method: stuSn === "new" ? "POST" : "PUT",
            headers: {
                "Content-Type": "application/json;charset=utf-8",
            },
            body: JSON.stringify(data),
        });

        if (!response.ok) {
            console.error(response);
            return;
        }
    };

    const deleteAction = async () => {
        let response = await fetch(`/api/student/${stuSn}`, {
            method: "DELETE",
        });

        if (!response.ok) {
            console.error(response);
            return;
        }

        navigate("/student/list");
    };

    if (error) {
        return (
            <div className="paper">
                <div>数据加载失败</div>
            </div>
        );
    }

    if (stuSn !== undefined && !stuinfo) {
        return (
            <div className="paper">
                <div>数据加载中...</div>
            </div>
        );
    }

    return (
        <div className="paper">
            <div className="paper-head">
                <h3>
                    {stuSn === "new"
                        ? "新建学生信息卡"
                        : `学生信息卡：${stuinfo.stu_name} (#${stuinfo.stu_sn})`}
                </h3>
            </div>
            <div className="paper-body">
                <form ref={formRef}>
                    <div className="field">
                        <label>学号: </label>
                        <input type="text" name="stu_no" />
                    </div>
                    <div className="field">
                        <label>姓名: </label>
                        <input type="text" name="stu_name" />
                    </div>
                    <div className="field">
                        <label>性别: </label>
                        <div className="radio-choices">
                            <span className="option">
                                男
                                <input type="radio" name="gender" value="m" />
                            </span>
                            <span className="option">
                                女
                                <input type="radio" name="gender" value="f" />
                            </span>
                        </div>
                    </div>
                    <div className="field">
                        <label>入学时间: </label>
                        <input type="date" name="enrolled" />
                    </div>
                </form>
            </div>
            <div className="paper-footer">
                <div className="btns">
                    <button className="btn" onClick={deleteAction}>
                        删除
                    </button>
                    <button className="btn" onClick={saveAction}>
                        保存
                    </button>
                    <button
                        className="btn"
                        onClick={() => {
                            navigate("/student/list");
                        }}
                    >
                        返回
                    </button>
                </div>
            </div>
        </div>
    );
}

export default StudentInfo;
